package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    @Autowired(required = false)
    private DishMapper dishMapper;
    @Autowired(required = false)
    private SetmealMapper setmealMapper;
    @Override
    public Page<Category> findByPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Category> categoryList = categoryMapper.findByPage();
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        Page<Category> categoryPage = new Page<>(pageInfo.getList(),pageInfo.getTotal(),pageInfo.getPageSize(),pageInfo.getPageNum());
        return categoryPage;
    }

    @Override
    public void save(Category category) {
        Category byName = categoryMapper.findByName(category.getName());
        if(byName !=null){
            throw new BusinessException("分类已存在,请重新输入分类名");
        }
        LocalDateTime now = LocalDateTime.now();
        category.setCreateTime(now);
        category.setUpdateTime(now);
        categoryMapper.save(category);
    }

    @Override
    public void update(Category category) {
        Category byName = categoryMapper.findByName(category.getName());
        if(byName !=null){
            throw new BusinessException("分类名已存在,修改失败");
        }
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.update(category);
    }

    @Override
    public void delete(Long id) {
        Integer dishByCategoryId = dishMapper.findByCategoryId(id);
        if(dishByCategoryId>0){
            throw new BusinessException("该类别有关联的菜品无法删除");
        }
        Integer setmealByCategoryId = setmealMapper.findByCategoryId(id);
        if(setmealByCategoryId>0){
            throw new BusinessException("该类别有关联的套餐无法删除");
        }
        categoryMapper.delete(id);
    }

    public List<Category> findByType(Integer type){
        List<Category> byType = categoryMapper.findByType(type);
        return byType;
    }
}

